# -*- coding: utf-8 -*-            
# @Time : 2024/9/11 14:34
# @FileName: mongo.py
# @Target:
from pymongo import MongoClient


# class Mongo_Logger(object):
#     def __init__(self,
#                  Mongo_URL,
#                  Mongo_Port
#                  ):
#         client = MongoClient(
#             host=Mongo_URL,
#             port=Mongo_Port
#         )
#         db_client = client.get_database(
#             name='log'
#         )
#         self.logger_qwen2 = db_client[
#             'qwen2'
#         ]
#
#     def insert_log(self, dic):
#         self.logger_qwen2.insert_one(dic)
#
#
#
#
#
#
# if __name__ == '__main__':
#     logger = Mongo_Logger()
#     logger.insert_log_qwen2({'aaa' : 'ccc'})



"""

class Mongo_GridFS(object):
    def __init__(self,
                 Mongo_URL="123.58.213.162",
                 Mongo_Port=27017,
                 data_base_name="images",
                 image_collection_name="images"):
        client = MongoClient(host=Mongo_URL, port=Mongo_Port)
        db_client = client.get_database(name=data_base_name)
        self.gridfs_images = GridFS(database=db_client, collection=image_collection_name)

    def insert_image(self, image_url, image_base64_str):
        if not self.find_image_url(image_url=image_url):
            dic = dict(image_url=image_url)
            self.gridfs_images.put(image_base64_str, **dic)

    def find_image_url(self, image_url):
        return self.gridfs_images.find_one({"image_url": image_url})


class Idata_API_Mongo_Client(object):
    def __init__(self,
                 mongo_url="123.58.213.162",
                 data_base_name="articles",
                 article_collection_name="articles",
                 images_collection_name="images",
                 port=27017):
        mongo_client = MongoClient(host=mongo_url, port=port).get_database(name=data_base_name)
        self.article_mongo = mongo_client[article_collection_name]
        self.mongo_gridfs = Mongo_GridFS(Mongo_URL=mongo_url, Mongo_Port=port, data_base_name=data_base_name, image_collection_name=images_collection_name)

    def insert_article(self, dic):
        self.article_mongo.insert(dic)

    def insert_image(self, img_url, img_base64_str):
        self.mongo_gridfs.insert_image(image_url=img_url, image_base64_str=img_base64_str)

    def find_image(self, img_url, base64_str=True):
        image_base64 = self.mongo_gridfs.find_image_url(image_url=img_url).read()
        if not base64_str:
            image_base64 = base64.b64decode(image_base64)
        return image_base64


"""